package com.lj.graduate.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lj.graduate.common.Constants;
import com.lj.graduate.common.Result;
import com.lj.graduate.controller.dto.AdminDTO;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.lj.graduate.service.IAdminService;
import com.lj.graduate.entity.Admin;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ljy
 * @since 2023-03-23
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    
@Resource
private IAdminService adminService;


// 新增或者更新
@PostMapping
public Result save(@RequestBody Admin admin) {
        return Result.success(adminService.saveOrUpdate(admin));
        }

@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id) {
        return Result.success(adminService.removeById(id));
        }

@PostMapping("/del/batch")
public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(adminService.removeByIds(ids));
        }

@GetMapping
public List<Admin> findAll() {
        return adminService.list();
        }

@GetMapping("/{id}")
public Admin findOne(@PathVariable Integer id) {
        return adminService.getById(id);
        }

@GetMapping("/page")
public Page<Admin> findPage(@RequestParam Integer pageNum,
@RequestParam Integer pageSize) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        return adminService.page(new Page<>(pageNum, pageSize), queryWrapper);
}
        /**
         * 导出接口
         */
        @GetMapping("/export")
        public void export(HttpServletResponse response) throws Exception {
                // 从数据库查询出所有的数据
                List<Admin> list = adminService.list();
                // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
                // 在内存操作，写出到浏览器
                ExcelWriter writer = ExcelUtil.getWriter(true);
                //自定义标题别名
                writer.addHeaderAlias("administratorId","id");
                writer.addHeaderAlias("administratorAccount", "用户名");
                writer.addHeaderAlias("authority", "权限");
                writer.addHeaderAlias("administratorPassword", "密码");
                writer.addHeaderAlias("avatarurl", "头像");
                writer.setOnlyAlias(true);
                // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
                writer.write(list, true);

                // 设置浏览器响应的格式
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
                String fileName = URLEncoder.encode("管理员信息", "UTF-8");
                response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

                ServletOutputStream out = response.getOutputStream();
                writer.flush(out, true);
                out.close();
                writer.close();

        }

        /**
         * excel 导入
         * @param file
         * @throws Exception
         */
        @PostMapping("/import")
        public Boolean imp(MultipartFile file) throws Exception {
                InputStream inputStream = file.getInputStream();
                ExcelReader reader = ExcelUtil.getReader(inputStream);
                // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
//        List<User> list = reader.readAll(User.class);

                // 方式2：忽略表头的中文，直接读取表的内容
                List<List<Object>> list = reader.read(1);
                List<Admin> admins = CollUtil.newArrayList();
                for (List<Object> row : list) {
                        Admin admin = new Admin();
                        admin.setAdministratorAccount(row.get(0).toString());
                        admin.setAdministratorPassword(row.get(1).toString());
                        admin.setAuthority((row.get(2).toString()));

                        admins.add(admin);
                }

                adminService.saveBatch(admins);
                return true;
}
        @PostMapping("/login")
        public Result login(@RequestBody AdminDTO adminDTO) {
                String account = adminDTO.getAdministratorAccount();
                String password = adminDTO.getAdministratorPassword();
                if (StrUtil.isBlank(account) || StrUtil.isBlank(password)) {
                        return Result.error(Constants.CODE_400,"参数错误");
                }
                AdminDTO adminDTO1 = adminService.login(adminDTO);
                return Result.success(adminDTO1);
        }

        @GetMapping("/Account/{administratorAccount}")
        public Result findOne(@PathVariable String administratorAccount){
                QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("administrator_account",administratorAccount);
                return Result.success(adminService.getOne(queryWrapper));
        }

        }

